[Web] 轉換 [icon svg] 為 [background-image]


Posted by mike-hsieh on 2023-07-06

因近期優化一些專案的前端樣式,有一個將svg轉background-image的方式,在此紀錄:

  1. 先找到自己喜歡的Icon,目前Fontawsome有免費的可以抓:
    https://fontawesome.com/search?o=r&m=free

  2. 調整icon樣式後,取得svg:

  3. 對svg的原始碼進行Url編碼(google也找的到線上轉換):

  4. 取得編碼後,就可以在css產生background-image了,範例如下:

    background-image: url("data:image/svg+xml,這邊插入url編碼");
    
  5. 實務上範例,用在欄位必填星號上,直接用class就可以,不用手動寫span標籤了(需要請自取):

    /*必填提示星號*/
    .fill-hint-star {
     background-image: url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20height%3D%221em%22%20viewBox%3D%220%200%20512%20512%22%3E%3Cstyle%3Esvg%7Bfill%3A%23dc143c%7D%3C%2Fstyle%3E%3Cpath%20d%3D%22M208%2032c0-17.7%2014.3-32%2032-32h32c17.7%200%2032%2014.3%2032%2032V172.9l122-70.4c15.3-8.8%2034.9-3.6%2043.7%2011.7l16%2027.7c8.8%2015.3%203.6%2034.9-11.7%2043.7L352%20256l122%2070.4c15.3%208.8%2020.5%2028.4%2011.7%2043.7l-16%2027.7c-8.8%2015.3-28.4%2020.6-43.7%2011.7L304%20339.1V480c0%2017.7-14.3%2032-32%2032H240c-17.7%200-32-14.3-32-32V339.1L86%20409.6c-15.3%208.8-34.9%203.6-43.7-11.7l-16-27.7c-8.8-15.3-3.6-34.9%2011.7-43.7L160%20256%2038%20185.6c-15.3-8.8-20.5-28.4-11.7-43.7l16-27.7C51.1%2098.8%2070.7%2093.6%2086%20102.4l122%2070.4V32z%22%2F%3E%3C%2Fsvg%3E");
     background-repeat: no-repeat !important;
     background-position: right !important;
     background-size: 6.5px;
    }
    


#svg #background-image







Related Posts

秘密:十週年紀念版

秘密:十週年紀念版

我的gulpfile.js要怎麼撰寫

我的gulpfile.js要怎麼撰寫

27. Comparison of Design Patterns

27. Comparison of Design Patterns


Comments